package com.example.leepong.Game;

import com.example.leepong.Game.Shapes.Coordinates;
import com.example.leepong.Game.Utils.Canceller;

import java.util.ArrayList;

/**
 * Created by Ichigo on 28/02/14.
 */
public class CoordinatesMover {
    public static void MoveAsync(final Coordinates current,final Coordinates target, final int speed, final Canceller.RunToken Token) {

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                MoveAction(current, target, speed, Token);
            }
        });
        thread.start();
    }

    private static void MoveAction(Coordinates current, Coordinates target, int speed, Canceller.RunToken Token) {
        ArrayList<Coordinates> path = GetPath(current, target);
        for (Coordinates coord : path) {
            if (Token.IsCancelled) {
                //   Log.D("----", "cancelled:" + path.IndexOf(coord));
                return;
            }

            try {
                Thread.sleep(speed);
            } catch (InterruptedException ex) {
            }

            current.X = coord.X;
            current.Y = coord.Y;
        }

        current.X = target.X;
        current.Y = target.Y;
    }

    private static ArrayList<Coordinates> GetPath(Coordinates current, Coordinates target) {
        float length = 10.0f;
        ArrayList<Coordinates> rawPath = new ArrayList<Coordinates>();
        float xfrag = (target.X - current.X) / length;
        float yfrag = (target.Y - current.Y) / length;

        Coordinates coord = new Coordinates();
        coord.X = current.X + xfrag;
        coord.Y = current.Y + yfrag;
        rawPath.add(coord);

        for (int i = 0; i < length - 1; i++) {
            Coordinates before = rawPath.get(i);
            Coordinates temp = new Coordinates();
            temp.X = before.X + xfrag;
            temp.Y = before.Y + yfrag;
            rawPath.add(temp);
        }

        return rawPath;
    }


    public static void Move(Coordinates current, int angle, float step) {
        double piAngle = Math.PI * (angle / 180.0f);
        current.X = (float) (current.X + (step * Math.cos(piAngle)));
        current.Y = (float) (current.Y + (step * Math.sin(piAngle)));
     //   Log.d("----", "draw real X" + current.X);
    }
}
